import React, { useState, useEffect } from 'react';
import {
  Input,
  Select,
  DatePicker,
  Button,
  Table,
  Space,
  Tag,
  Popconfirm,
  Form,
  Pagination,
  message,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import PublicModal from '../../component/publicModal/PublicModal';
import {
  getOutboundRecords,
  addOutboundRecord,
  updateOutboundRecord,
  deleteOutboundRecord,
  OutboundRecord,
} from '../../api/outbound';

const { RangePicker } = DatePicker;
const { Option } = Select;




const Ckgl = () => {
  // 数据状态
  const [dataSource, setDataSource] = useState<OutboundRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 查询的参数
  const [, setSearchParams] = useState({
    outboundNumber: '',
    outboundType: '',
    customerName: '',
    outboundTime: null,
  });

  const formItems: Array<{
    name: string;
    label: string;
    type?: 'input' | 'select';
    options?: Array<{ value: string; label: string }>;
  }> = [
    { name: 'code', label: '出库单号' },
    { 
      name: 'type', 
      label: '出库类型',
      type: 'select',
      options: [
        { value: '普通出库', label: '普通出库' },
        { value: '退货出库', label: '退货出库' },
      ]
    },
    { name: 'name', label: '客户名称' },
    { name: 'total', label: '订单总件数' },
    { name: 'issued', label: '已出数量' },
  ];

  // 表单显示
  const [visibity, setVisibity] = useState(false);
  // 表单标题
  const [title, setTitle] = useState('新增出库单');
  // 编辑的记录
  const [editingRecord, setEditingRecord] = useState<OutboundRecord | null>(null);

  // 获取查询的表单
  const [searchForm] = Form.useForm();

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const data = await getOutboundRecords();
      setDataSource(data);
      setPagination(prev => ({ ...prev, total: data.length }));
    } catch {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadData();
  }, []);

  // 点击查询按钮执行
  const handleOutSearch = (values: Record<string, unknown>) => {
    setSearchParams(values as Record<string, unknown>);
    // 这里可以实现搜索逻辑
    console.log('查询参数:', values);
  };

  // 处理添加出库单
  const handleAddOutbound = () => {
    setEditingRecord(null);
    setTitle('新增出库单');
    setVisibity(true);
  };

  // 处理编辑出库单
  const handleEditOutbound = (record: OutboundRecord) => {
    setEditingRecord(record);
    setTitle('编辑出库单');
    setVisibity(true);
  };

  // 处理删除出库单
  const handleDeleteOutbound = async (record: OutboundRecord) => {
    try {
      await deleteOutboundRecord(record.id!);
      message.success('删除成功');
      loadData();
    } catch {
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values: Record<string, unknown>) => {
    try {
      if (editingRecord) {
        await updateOutboundRecord(editingRecord.id!, values);
        message.success('更新成功');
      } else {
        await addOutboundRecord(values as Omit<OutboundRecord, 'id'>);
        message.success('添加成功');
      }
      setVisibity(false);
      loadData();
    } catch {
      message.error(editingRecord ? '更新失败' : '添加失败');
    }
  };

  const columns = [
    {
      title: '',
      dataIndex: 'check',
      render: () => <Input type="checkbox" />,
    },
    {
      title: '出库编号',
      dataIndex: 'code',
    },
    {
      title: '状态',
      dataIndex: 'flag',
      render: (flag: boolean) => (
        <Tag color={flag ? 'green' : 'blue'}>{flag ? '出库完成' : '初始录入'}</Tag>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
    },
    {
      title: '明细',
      dataIndex: 'details',
      render: (_, record: OutboundRecord) =>
        !record.flag ? (
          <Space>
            <FileTextOutlined />
            <PlusOutlined style={{ backgroundColor: '#000', color: '#fff', borderRadius: '50%', padding: '4px' }} />
          </Space>
        ) : (
          <FileTextOutlined />
        ),
    },
    {
      title: '客户名称',
      dataIndex: 'name',
    },
    {
      title: '订单总件数',
      dataIndex: 'total',
    },
    {
      title: '已出数量',
      dataIndex: 'issued',
    },
    {
      title: '订单日期',
      dataIndex: 'time',
    },
    {
      title: '出库时间',
      dataIndex: 'outtime',
    },
    {
      title: '操作',
      render: (_, record: OutboundRecord) => {
        return (
          <Space>
            <Button onClick={() => handleEditOutbound(record)}>编辑</Button>
            <Popconfirm 
              title="确定删除吗？" 
              okText="确定" 
              cancelText="取消"
              onConfirm={() => handleDeleteOutbound(record)}
            >
              <Button>删除</Button>
            </Popconfirm>
          </Space>
        );
      }
    }
  ];
  return (
    <div style={{ padding: '20px' }}>
      <Form
        form={searchForm}
        onFinish={handleOutSearch}
        layout="inline"
        style={{
          marginBottom: '20px'
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%'
          }}
        >
          <Space>
            <Form.Item
              name="outboundNumber"
              rules={[{ whitespace: true }]} // 允许空值，但不允许纯空格
            >
              <Input
                placeholder="请输入出库单号"
                prefix={<SearchOutlined />}
                style={{ width: 150 }}
              />
            </Form.Item>

            <Form.Item name="outboundType">
              <Select placeholder="请选择出库类型" style={{ width: 150 }}>
                <Option value="normal">普通出库</Option>
                <Option value="return">退货出库</Option>
              </Select>
            </Form.Item>

            <Form.Item name="customerName">
              <Input
                placeholder="请输入客户名称"
                prefix={<SearchOutlined />}
                style={{ width: 150 }}
              />
            </Form.Item>


          </Space>

          <Space>
            <span>出库时间:</span>
            <Form.Item name="outboundTime">
              <RangePicker style={{ marginRight: 10 }} />
            </Form.Item>
          </Space>
        </div>
        <div style={{ width: '100%', textAlign: 'end', marginTop: '20px', marginRight: '25px' }}>
          <Space>
            <Button type="primary" htmlType='submit'>搜索</Button>
            <Button htmlType='reset'>重置</Button>
          </Space>
        </div>

        <Space style={{ marginBottom: '20px', marginTop: '20px' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddOutbound}>
            添加出库
          </Button>
        </Space>
      </Form>
      <Table 
        dataSource={dataSource} 
        columns={columns} 
        pagination={false}
        loading={loading}
        rowKey="id"
      />

      {/* 分页区域 */}
      <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Pagination
          current={pagination.current}
          total={pagination.total}
          pageSize={pagination.pageSize}
          onChange={(page, pageSize) => {
            setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 10 }));
          }}
        />
        <Space>
          <span>{pagination.pageSize}条/页</span>
          <span>跳至</span>
          <Input 
            type="text" 
            defaultValue="1" 
            style={{ width: 50, textAlign: 'center' }}
            onPressEnter={(e) => {
              const page = parseInt((e.target as HTMLInputElement).value);
              if (page > 0 && page <= Math.ceil(pagination.total / pagination.pageSize)) {
                setPagination(prev => ({ ...prev, current: page }));
              }
            }}
          />
          <span>页</span>
        </Space>
      </div>

      <PublicModal 
        formItems={formItems} 
        visibity={visibity} 
        setVisibity={setVisibity} 
        title={title}
        formParams={{
          initialValues: editingRecord,
          onSubmit: handleFormSubmit,
        }}
      />
    </div>
  );
};

export default Ckgl;
